//
//  ZTOrderDetailViewController.m
//  FD
//
//  Created by xiaofang wang on 2018/10/31.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  @"自提订单详情"
//和外送订单详情数据结构好像是一样的。复用。
//1-22重写
//controler
#import "ZTOrderDetailViewController.h"
#import "EvaluateController.h" //评价复用
#import "WSZaiLaiYiDanViewController.h" //再来一单
#import "WSPayUrlViewController.h" //网页支付

//view
#import "WSOrderDetailCell.h" //复用
#import "WSOrderDetailSectionHeaderView.h" //复用
#import "ZTDetailHeaderView.h" //tableview的头
#import "OrderFooterView.h" //表尾-复用
#import "XLAlertView.h" //弹框

//model
#import "WSOrderMsgModel.h" //复用(OrderFooterView中tableView的cell需要用到的数据)

//工具方法
#import "WSOrderDetailTableViewProxy.h" //抽取tableView代理方法
#import "WSOrderDetailDataResolveTool.h" //专门负责数据解析
#import "FDSystemTool.h" //弹框打电话
#import "FDPaytypeAlertTool.h" //2019-2-13

@interface ZTOrderDetailViewController ()<OrderFooterViewDelegate>
/**tableView*/
@property (nonatomic, strong) UITableView *tableView;
/**表头*/
@property (nonatomic, strong) ZTDetailHeaderView *headerView;
/**表尾*/
@property (nonatomic, strong) OrderFooterView *footerView;
/**tableViewProxy*/
@property (nonatomic, strong) WSOrderDetailTableViewProxy *tableViewProxy;

/**标记商家电话*/
@property (nonatomic, copy) NSString *shopPhone;

//标记标记paymentType&status处理按钮交互事件
/**paymentType*/
@property (nonatomic, strong) NSNumber *tempPaymentType;
/**status*/
@property (nonatomic, strong) NSNumber *tempStatus;
/**订单id*/
@property (nonatomic, strong) NSNumber *tempOrderId;

/**菊花盖住按钮防止重复点击*/
@property (nonatomic, strong) MBProgressHUD *hud;

@end


@implementation ZTOrderDetailViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    if (![NSString isEmptyString:self.orderId]) {
        [self loadZTOrderDetailDataWithOrderId:self.orderId];
    }
}


- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = NSLocalizedString(Home_OrderDetail, @"订单详情");
    
    self.tableView.frame = self.view.bounds;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
}


#pragma mark - OrderFooterViewDelegate

- (void)clickOrderFooterViewActionType:(OrderFooterViewActionType)actionType {
    if (actionType == OrderFooterViewActionLeft) { //左边
        
        [FDSystemTool fd_makePhone:self.shopPhone];
        
    }else if (actionType == OrderFooterViewActionTypeRight) {//右边
        FDLog(@"右边的按钮 处理按钮交互事件");
        
        [self ztHandleRightBtnAction];
    }
}

#pragma mark - 1-23处理右边按钮交互事件
/**
 问题:
 1.要么本类中定义属性标记status: paymentType  暂定这个✅
 
 2.要么block回调。
    VC --> OrderFooterView --> OrderFooterDownView -->
    VC <-- OrderFooterView <-- OrderFooterDownView <--
传进去在传出来。感觉更复杂
 */
- (void)ztHandleRightBtnAction {
    
    NSNumber *status = self.tempStatus;
    NSNumber *payment = self.tempPaymentType;
    
    //在线支付显示逻辑 payementType:0 status:0 显示
    //payementType:1 status:0,1,2,3 显示

    //再来一单显示逻辑 status:5,6,7,8,9 显示

    //评价显示逻辑 status:4

    if ([payment isEqualToNumber:@(0)] && [status isEqualToNumber:@(0)]) {
        [self ztHandlePayNow];
    }else if ([payment isEqualToNumber:@(1)]) {
        if ([status isEqualToNumber:@(0)] ||
            [status isEqualToNumber:@(1)] ||
            [status isEqualToNumber:@(2)] ||
            [status isEqualToNumber:@(3)]) {
            [self ztHandlePayNow];
        }else if([status isEqualToNumber:@(4)]) {
            [self ztHandleEvaluate];
        }
    }else if ([status isEqualToNumber:@(4)]) {
        [self ztHandleEvaluate];
    }else if ([status isEqualToNumber:@(5)] ||
              [status isEqualToNumber:@(6)] ||
              [status isEqualToNumber:@(7)] ||
              [status isEqualToNumber:@(8)] ||
              [status isEqualToNumber:@(9)]) { //再来一单
        [self ztHandleOrderAgain];
    }else if ([payment isEqualToNumber:@(0)]
              &&[status isEqualToNumber:@(3)]) { //2019-2-20 status:1/2/3都是 ‘再来一单’
        [self ztHandleOrderAgain];
    }else if ([payment isEqualToNumber:@(0)] &&
              [status isEqualToNumber:@(1)]) { //2019-2-20 status:1/2/3都是 ‘再来一单’
        [self ztHandleOrderAgain];

    }else if ([payment isEqualToNumber:@(0)] &&
              [status isEqualToNumber:@(2)]) { //2019-2-20 status:1/2/3都是 ‘再来一单’
        [self ztHandleOrderAgain];
    }else {
        FDLog(@"其他状态不处理 status:%@-paytype:%@",status,payment);
    }
}

//- (void)ztHandleRightBtnAction {
//
//    NSNumber *status = self.tempStatus;
//    NSNumber *payment = self.tempPaymentType;
//
//    if ([payment isEqualToNumber:@(0)] &&
//        [status isEqualToNumber:@(0)]) { //在线支付
//
//        [self ztHandlePayNow];
//
//    }else if([payment isEqualToNumber:@(1)]) {
//        if ([status isEqualToNumber:@(0)] ||
//            [status isEqualToNumber:@(1)] ||
//            [status isEqualToNumber:@(2)] ||
//            [status isEqualToNumber:@(3)]) { //在线支付
//
//            [self ztHandlePayNow];
//        }
//
//    }else if([status isEqualToNumber:@(4)]){ //评价
//
//        [self ztHandleEvaluate];
//
//    }else if([status isEqualToNumber:@(5)] ||
//             [status isEqualToNumber:@(6)] ||
//             [status isEqualToNumber:@(7)] ||
//             [status isEqualToNumber:@(8)] ||
//             [status isEqualToNumber:@(8)]) { //再来一单
//        [self ztHandleOrderAgain];
//
//    }else {
//        FDLog(@"其他情况不处理");
//    }
//}


//!!!!:0.评价
- (void)ztHandleEvaluate {
    FDLog(@"评价");
    
    EvaluateController *evaluateVC = [[EvaluateController alloc] init];
    evaluateVC.fdDeliveryType = FDDeliveryTypeZiTi;
    evaluateVC.userOrderId = self.orderId;
    
    [self.navigationController pushViewController:evaluateVC animated:YES];
}

//!!!!:1.再来一单
- (void)ztHandleOrderAgain {
    FDLog(@"再来一单");
    
    WSZaiLaiYiDanViewController *zlydVC = [[WSZaiLaiYiDanViewController alloc] init];
    zlydVC.userOrderId = self.orderId;
    [self.navigationController pushViewController:zlydVC animated:YES];
}


//!!!!:2.立即支付
- (void)ztHandlePayNow {
    [self ztHandlePayNowWithStatus:self.tempStatus paymentType:self.tempPaymentType];
}


- (void)ztHandlePayNowWithStatus:(NSNumber *)status paymentType:(NSNumber *)payment {
    FDLog(@"立即支付");
    
    if ([payment isEqualToNumber:@(1)]) { //弹框一个按钮
        if ([status isEqualToNumber:@(1)] ||
            [status isEqualToNumber:@(2)] ||
            [status isEqualToNumber:@(3)]) {
            
            [FDPaytypeAlertTool showAlertOnePayTypeOnlinePayBlock:^{
                [self ztHandlePayOnline];
            }];
        }
    }else if ([payment isEqualToNumber:@(0)] &&
              [status isEqualToNumber:@(0)]) { //弹框两个按钮
        
        [FDPaytypeAlertTool showAlertTwoPaytypePayOnlineBlock:^{
            [self ztHandlePayOnline];
        } offlineBlock:^{
            [self ztHandlePayOffline];
        }];
    }
}


//!!!!:2-1在线支付
- (void)ztHandlePayOnline {
    FDLog(@"在线支付");
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    //拿到支付链接
    [FDHttpAPi requestPayOnlineWithOrderId:self.orderId successBlock:^(id responseObjc) {
        
        [self.hud hideAnimated:YES];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSString *url = responseObjc[@"data"][@"url"];
         //跳转网页进行支付。
            WSPayUrlViewController *payurlVC = [[WSPayUrlViewController alloc] init];
            payurlVC.payUrl = url;
            [self.navigationController pushViewController:payurlVC animated:YES];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        
        [self.hud hideAnimated:YES];
    }];
}



//!!!!:2-1线下支付
- (void)ztHandlePayOffline {
    FDLog(@"线下支付");
    
    [FDHttpAPi requestPayOfflineWithOrderId:self.orderId successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            
            //刷新状态
            [self loadZTOrderDetailDataWithOrderId:self.orderId];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"在线支付失败:%@",[error localizedDescription]);
    }];
}


#pragma mark - 请求数据
- (void)loadZTOrderDetailDataWithOrderId:(NSString *)orderId {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [FDHttpAPi requestUserOrderDetailOrderId:orderId successBlock:^(id responseObjc) {
        [hud hideAnimated:YES];

        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSDictionary *dataDic = responseObjc[@"data"];
            
            //标记商家电话
            self.shopPhone = dataDic[@"shop"][@"phone"];
            
            [self assembleFooterViewTableViewDataWithDic:dataDic];//1-23解析表尾数据
            
            NSArray *proxyDataArr =  [WSOrderDetailDataResolveTool xinResolvingTableViewDataWithDic:dataDic];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.tableViewProxy.dataArray = proxyDataArr;
                [self.tableView reloadData]; //✅1-22
            });
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        [hud hideAnimated:YES];
    }];
}


/**1-23解析表位footerView的订单*/
- (void)assembleFooterViewTableViewDataWithDic:(NSDictionary *)dic {
    
    //一:优惠券数据
    NSNumber *couponAmount = dic[@"couponAmount"]; //优惠
    NSNumber *actualAmount = dic[@"actualAmount"]; //实际付款
    NSNumber *totalAmount = dic[@"totalAmount"];   //总价
    //二:配送费
    NSNumber *freightAmount = dic[@"freightAmount"];
    //三:已经优惠 合计
    CGFloat youhuiPrice = [totalAmount floatValue] - [actualAmount floatValue];
    //更新数据
    [self.footerView updateTopCouponFreightViewWithCoupon:couponAmount freight:freightAmount alreadyCoupon:youhuiPrice sum:actualAmount];
    
    //四:表位中的tableView中的数据
    NSString *orderNumber = dic[@"id"];
    NSNumber *paymentType = dic[@"paymentType"];
    NSString *payTypeStr = @"";
    if ([paymentType isEqualToNumber:@(0)]) {
        payTypeStr = NSLocalizedString(L_Pay_Online, @"在线支付");;
    }else {
        payTypeStr = NSLocalizedString(L_Pay_Offline_Cash, @"线下支付");
    }
    NSString *xinZhenJiFen = [NSString stringWithFormat:@"%@",dic[@"bonusAmount"]];
    NSString *remark = dic[@"remark"] ? : @"";
 
    

    //国际化
    NSString *ddhStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(OrderNumber, @"订单号:")];
    NSString *zffsStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(Order_PayType, @"支付方式:")];
    NSString *xzjfStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(XinZhengJiFen, @"新增积分:")];
    NSString *bzStr = [NSString stringWithFormat:@"%@:",NSLocalizedString(Order_Remark, @"备注")];
    
    NSArray *footerTableViewDataArr = @[@{@"title":ddhStr,@"content":orderNumber},
                         @{@"title":zffsStr,@"content":payTypeStr},
                         @{@"title":xzjfStr,@"content":xinZhenJiFen},
                         @{@"title":bzStr,@"content":remark}
                         ];
    NSMutableArray *tempFooterTableViewDataArrM = @[].mutableCopy;
    //转模型
    for (NSDictionary *dic in footerTableViewDataArr) {
        WSOrderMsgModel *model = [WSOrderMsgModel mj_objectWithKeyValues:dic];
        [tempFooterTableViewDataArrM addObject:model];
    }
    [self.footerView updateCenterTableViewDataArray:tempFooterTableViewDataArrM];
    
    
    
    //五:更新footerVeiw的footerView的按钮文字状态
    NSNumber *status = dic[@"status"];
    [self.footerView updateRightBtnTitleWithStatus:status payType:paymentType deliveryType:@(1)]; //deliveryType:1、自提
    
    //六:标记status、paymentType ==>据此判断按钮交互事件
    self.tempStatus = status;
    self.tempPaymentType = paymentType;
}



#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
        //代理
        _tableView.delegate = self.tableViewProxy;
        _tableView.dataSource = self.tableViewProxy;
        
       //注册
        [_tableView registerClass:[WSOrderDetailCell class] forCellReuseIdentifier:@"WSOrderDetailCell"];
        [_tableView registerClass:[WSOrderDetailSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"WSOrderDetailSectionHeaderView"]; //sectionHeaderView
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone; //取消线
        _tableView.backgroundColor = [UIColor whiteColor]; //1-23防止屏幕太大,一屏放不下。就特丑。
    }
    return _tableView;
}

- (WSOrderDetailTableViewProxy *)tableViewProxy {
    if (!_tableViewProxy) {
        _tableViewProxy = [[WSOrderDetailTableViewProxy alloc] init];
    }
    return _tableViewProxy;
}


- (ZTDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZTDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];//10+60 + 10
    }
    return _headerView;
}

- (OrderFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[OrderFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
        _footerView.backgroundColor = [UIColor yellowColor];
        _footerView.delegate = self; //OrderFooterViewDelegate
    }
    return _footerView;
}

@end
